import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';

const CategoryForm = ({ visible, onCancel, onSubmit, category, title }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible && category) {
      form.setFieldsValue(category);
    } else if (visible) {
      form.resetFields();
    }
  }, [visible, category, form]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      await onSubmit(values);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        name="categoryForm"
      >
        <Form.Item
          name="name"
          label="分类名称"
          rules={[
            { required: true, message: '请输入分类名称' },
            { min: 2, message: '分类名称至少2个字符' },
            { max: 50, message: '分类名称最多50个字符' }
          ]}
        >
          <Input placeholder="请输入分类名称" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CategoryForm;
